﻿using System;
using Microsoft.Xna.Framework;

namespace Ratatoskr
{
    public class UpdateServer : UpdateServer<Component>
    {
        public UpdateServer(string type, bool open = true, bool single = false)
            : base(type, open, single)
        {
        }

        public UpdateServer(bool open = true, bool single = false)
            : base(open, single)
        {
        }
    }


    public class UpdateServer<T> : ServerComponent<T> where T : class
    {
        protected GameTime _gt;

        public UpdateServer(string type, bool open = true, bool single = false)
            : base(type, open, single)
        {
        }

        public UpdateServer(bool open = true, bool single = false)
            : this("UpdateServer", open, single)
        {
        }

        protected override ServerComponentEventArgs ComposeArgs(object[] args = null)
        {
            return new ServerComponentEventArgs(new object[] { _gt, args });
        }

        public virtual void UseGameTime(GameTime gameTime)
        {
            _gt = gameTime;
        }

        protected override bool ExtendTriggerConditions()
        {
            return (_gt != null);
        }
    }


    public class IntermittentUpdateServer : IntermittentUpdateServer<Component>
    {
        public IntermittentUpdateServer(int interval, string type, bool open = true, bool single = false)
            : base(interval, type, open, single)
        {
        }
    }


    public class IntermittentUpdateServer<T> : UpdateServer<T> where T : class
    {
        protected int _interval;
        public int Interval
        {
            get { return _interval; }
            set { _interval = value; }
        }

        protected int _timer;
        public int Remaining
        {
            get { return _timer; }
        }

        public IntermittentUpdateServer(int interval, string type, bool open = true, bool single = false)
            : base(type, open, single)
        {
            _interval = interval;
            _timer = interval;
        }

        protected override bool ExtendTriggerConditions()
        {
            if (_gt == null)
                return false;
            _timer -= _gt.ElapsedGameTime.Milliseconds;
            if (_timer <= 0)
            {
                if (Math.Abs(_timer) >= _interval)
                    _timer = _interval;
                else _timer += _interval;
                return true;
            }
            return false;
        }

        public void ResetTimer()
        {
            _timer = _interval;
        }

        public override void UseGameTime(GameTime gameTime)
        {
            if (_gt != gameTime)
                ResetTimer();
            _gt = gameTime;
        }
    }
}